package com.audaque.springboot.foshanupload.web.nosaveframeworkloginvalid.interceptor;


import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.authcore.properties.LoginProperties;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.web.properties.IgnoreResourcePathProperties;
import com.audaque.springboot.foshanupload.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zgb
 * @desc 检查是否已登录
 * @date 2022-06-16 18:37:27
 */
//通过配置order()的值，值越小，优先级越高。不配默认是0

@Slf4j
public class NeedLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginProperties loginProperties;
    @Autowired
    private IgnoreResourcePathProperties ignoreResourcePathProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //int i=1/0;
        TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();
        if (transmittableThreadLocalCurrentUser != null) {
            return true;
        }

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");


        R r = new R();
        r.setSuccess(false);
        r.setStatus(ResultCodeEnum.NOT_LOGIN.getStatus());
        r.setDescription(ResultCodeEnum.NOT_LOGIN.getDescription());
        response.getWriter().write(JSONUtil.toJsonStr(r));
        return false;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 @Nullable Exception ex) throws Exception {
        TransmittableThreadLocalCurrentUser.remove();
    }

}
